package com.yoki.cloud.common.protocol.radius.attribute.attr.check;

import com.yoki.cloud.common.protocol.radius.attribute.attr.RadiusMsgAttr;
import com.yoki.cloud.common.utils.encrypt.EncryptUtils;

/**
 * @author Sky$
 * @Description: TODO
 * @date 2018/1/15$ 14:54$
 */
public class ChapPasswordAttr extends RadiusMsgAttr<byte[]> {

    public static final int ATTR_TYPE = 3;

    private ChapChallengeAttr chapChallengeAttr;

    public ChapPasswordAttr(ChapChallengeAttr chapChallengeAttr) {
        this.chapChallengeAttr = chapChallengeAttr;
    }

    @Override
    public int getAttrType() {
        return ATTR_TYPE;
    }

    @Override
    protected byte[] parseValue(byte[] input) {
        return input;
    }

    @Override
    protected byte[] getValueBytes() {
        return this.value;
    }

    /**
     * Encodes a plain-text password using the given CHAP challenge.
     *
     * @param plaintext plain-text password
     * @return CHAP-encoded password
     */
    public void encodeChapPassword(String plaintext) {
        this.value = EncryptUtils.encryptCHAP(this.chapChallengeAttr.getValue().getBytes(), plaintext.getBytes());
    }

    /**
     * Verifies a CHAP password against the given plaintext password.
     *
     * @return plain-text password
     */
    private boolean verifyChapPassword(String plaintext){
        return EncryptUtils.verifyCHAP(this.chapChallengeAttr.getValue().getBytes(), this.getValueBytes(), plaintext.getBytes());
    }

}
